/*!
 @header StatisticViewController.m
 @author 王 文彬
 @version 1.0.0 2013/02/05 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "StatisticListViewController.h"
#import "Config.h"
#import "Helper.h"
#import "RTLabel.h"
#import "JMFBase.h"
#import "MJRefresh.h"

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：StatisticListViewController功能较为简单，实现刷新基类的代理方法，就可以实现上拉和加载更多的功能。并且区分推荐与被推荐。
//  	<实现描述>：下拉：应重写并调用BaseRefreshViewController的reloadTableViewDataSource方法，在方法中实现自己的刷新数据源的方法。
//                加载更多：应重写并调用BaseRefreshViewController的refreshButtonEvent:方法，触发加载更多按钮事件。
//      <注意事项>：1、刷新时机，即_reloading，已经启动刷新时应将_reloading设为YES，防止刷新重复进行，刷新结束应将_reloading设为NO，准备下次刷新。
//                2、_isFooterRefresh，用于判断是否是加载更多，便于需要同时用到下拉和加载更多的地方判断如何刷新数据源。
//                《更多实现详见BaseRefreshViewController.m》
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>
@interface StatisticListViewController ()<MJRefreshBaseViewDelegate>

@end

@implementation StatisticListViewController
{
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}

@synthesize recommendType = _recommendType;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //导航按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    _dataSource = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    //    _blankPage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, _SYS_SCREEN_HEIGHT - 44.0f - 20.0f)];
    _blankPage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 832.0f/2.0f)];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*!
 @abstract 属性recommendType的setter方法实现
 @param recommendType NSInteger类型，为0时表示此列表应该显示你推荐的，为1时列表应该显示被推荐的
 */
- (void)setRecommendType:(NSInteger)recommendType
{
    _recommendType = recommendType;
    
    if (recommendType == 0) {
        self.title = _L(@"title_statistic_03");
    }
    else {
        self.title = _L(@"title_statistic_04");
    }
}

// 界面将显示时，刷新数据
//
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self statisticsRequestByCheckId:nil];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, 50, 50)];
        imageView.backgroundColor = [UIColor redColor];
        
        [cell.contentView addSubview:imageView];
        
        
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, 120, 15)];
        nameLabel.textColor = _SYS_COLOR_002;
        nameLabel.font = _SYS_FONT_003;
        
        [cell.contentView addSubview:nameLabel];
        
        
        RTLabel* dealLabel = [[RTLabel alloc] initWithFrame:CGRectMake(80, 27, 100, 15)];
        dealLabel.font = _SYS_FONT_001;
        
        [cell.contentView addSubview:dealLabel];
        
        
        RTLabel* amountLabel = [[RTLabel alloc] initWithFrame:CGRectMake(190, 27, 100, 15)];
        amountLabel.font = _SYS_FONT_001;
        
        [cell.contentView addSubview:amountLabel];
        
        
        RTLabel* pointLabel = [[RTLabel alloc] initWithFrame:CGRectMake(80, 44, 100, 15)];
        pointLabel.font = _SYS_FONT_001;
        
        [cell.contentView addSubview:pointLabel];
        
        
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
    }
    
    NSString* previewURL = [[_dataSource objectAtIndex:indexPath.row] valueForKey:@"picturePreview"];
    
    ((UIImageView *)[cell.contentView.subviews objectAtIndex:0]).image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:previewURL]]];
    ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).text = [[_dataSource objectAtIndex:indexPath.row] valueForKey:@"productName"];
    
    //你推荐的
    if (_recommendType == 0) {
        ((RTLabel *)[cell.contentView.subviews objectAtIndex:2]).text = [NSString stringWithFormat:DEAL_COUNT_STRING, [[[_dataSource objectAtIndex:indexPath.row] valueForKey:@"dealCount"] intValue]];
        ((RTLabel *)[cell.contentView.subviews objectAtIndex:3]).text = [NSString stringWithFormat:AMOUNT_COUNT_STRING, [[[_dataSource objectAtIndex:indexPath.row] valueForKey:@"dealAmount"] floatValue]];
        ((RTLabel *)[cell.contentView.subviews objectAtIndex:4]).text = [NSString stringWithFormat:POINT_COUNT_STRING, [[[_dataSource objectAtIndex:indexPath.row] valueForKey:@"pointsCount"] intValue]];
    }else{
        
        //被推荐的
        ((RTLabel *)[cell.contentView.subviews objectAtIndex:2]).text = [NSString stringWithFormat:RECOMMEND_COUNT, [[[_dataSource objectAtIndex:indexPath.row] valueForKey:@"beCount"] intValue]];
        ((RTLabel *)[cell.contentView.subviews objectAtIndex:3]).text = [NSString stringWithFormat:DEAL_COUNT_STRING, [[[_dataSource objectAtIndex:indexPath.row] valueForKey:@"beDealCount"] intValue]];
        ((RTLabel *)[cell.contentView.subviews objectAtIndex:4]).text = [NSString stringWithFormat:AMOUNT_COUNT_STRING, [[[_dataSource objectAtIndex:indexPath.row] valueForKey:@"beDealAmount"] floatValue]];
        
    }
    
    
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:false];
}


- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

#pragma mark - 私有方法

- (void)statisticsRequestByCheckId:(NSInteger)checkId
{
    NSString* urlString = _recommendType ? _JSON_URL_RECOMMEND_STATISTICS_PASSIVE_LIST : _JSON_URL_RECOMMEND_STATISTICS_ACTIVE_LIST;
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:urlString];
    request.delegate = self;
    
    //id不为空，说明用户在加载更多
    if(checkId != 0){
        
        [request setValue:@(checkId) forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreStatiisticsDidReceived:)];
    }
    
    [request asynchronous];
}


/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (NSInteger)catchTheLastDataSourceId
{
    if (_dataSource.count != 0) {
        
        return [[[_dataSource objectAtIndex:(_dataSource.count - 1)] objectForKey:@"id"] integerValue];
    }
    return 0;
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}


#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void)backButtonEvent
{
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_dataSource.count != 0) {
            [_dataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = self.tableView;
        }
        
        if (_dataSource.count > 0) {
            self.tableView.tableFooterView.hidden = NO;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
    
    //空页面的友好显示
    if (_dataSource.count == 0) {
        
        //页面类型：被推荐或推荐
        switch (_recommendType) {
                
            case 0:
            {
                _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_005@2x" ofType:@"png"]];
                
            }
                break;
                
            default:
            {
                _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_001@2x" ofType:@"png"]];
            }
                break;
        }
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_blankPage];
        
    }else{
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [_blankPage removeFromSuperview];
    }
}

- (void)moreStatiisticsDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}
//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunreachable")];
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self statisticsRequestByCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        if ([self catchTheLastDataSourceId] != 0) {
            [self statisticsRequestByCheckId:[self catchTheLastDataSourceId]];
        }
    }
}
@end